
package security.beans;

import Entity.Rol;
import Entity.TableModelRol;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import login.beans.ConectionBean;
import org.primefaces.event.RowEditEvent;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import security.business.RolBusiness;

/**
 *
 * @author JuanFelipe
 */

@ManagedBean
@ViewScoped
public class RolBean implements Serializable{
    
    private List<Rol> roles;
    private Rol selectedRol;
    private TableModelRol tableModel;
    private Connection  conn;
    private int ntab;
    private DualListModel< String > privileges;
    
    public RolBean( ) {
        /**
         * Otra forma de hacer pasar el valor del bean 
         */
        ntab = 0;
        System.out.println("ACA !");
        FacesContext context = javax.faces.context.FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        ConectionBean conectionBean =(ConectionBean) session.getAttribute("conectionBean");
        this.conn = conectionBean.currentConnection;
        System.out.println("ACA 2");
        selectedRol = new Rol("", "");
        init();
        System.out.println("ACA 3");
    }
    
    private void init() {
        try {
            roles = new RolBusiness( conn ).getRol();
            tableModel = new TableModelRol( roles );
        } catch (SQLException ex) {
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Please Try Again!",
                    ex.getMessage()));
        } 
    }

    public List<Rol> getRoles() {
        return roles;
    }

    public void setRoles(List<Rol> roles) {
        this.roles = roles;
    }

    public Rol getSelectedRol() {
        return selectedRol;
    }

    public void setSelectedRol(Rol selectedRol) {
        this.selectedRol = selectedRol;
    }

    public TableModelRol getTableModel() {
        return tableModel;
    }

    public void setTableModel(TableModelRol tableModel) {
        this.tableModel = tableModel;
    }

    public int getNtab() {
        return ntab;
    }

    public void setNtab(int ntab) {
        this.ntab = ntab;
    }

    public DualListModel<String> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(DualListModel<String> privileges) {
        this.privileges = privileges;
    }
    
    
    public void delete(  ){
        FacesMessage msg = new FacesMessage();  
        
        if( selectedRol!=null && !selectedRol.getName().equals("") ){
            
            System.out.println("ACA");
            System.out.println("NAME: "+ ( (selectedRol!=null)? selectedRol.getName():"NULL") );
            
            RolBusiness rb = new RolBusiness( conn );
            try {
                rb.delete( selectedRol.getName() );
                
                msg.setSeverity(FacesMessage.SEVERITY_INFO);  
                msg.setSummary("Rol Eliminado");
                msg.setDetail("Rol eliminado Exitosamente");  
                
                roles.remove( selectedRol );
                tableModel = new TableModelRol( roles );
                selectedRol = null;
                FacesContext.getCurrentInstance().addMessage(null, msg);  
            } catch (SQLException ex) {
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);  
                msg.setSummary("Error al eliminar");
                msg.setDetail("El rol no pudo ser eliminado "+ ex.getMessage() );  
            }
            
            selectedRol = null;
        }
    }
    
    
    
    
    public void edit() {  
        FacesMessage msg;
        System.out.print("EDIT!!!!! >>>");
        
        ntab = 2;
        
        msg = new FacesMessage("Puede Editar!", "Rol: "+selectedRol.getName());  
        chargeData();
        msg.setSeverity(FacesMessage.SEVERITY_INFO);
        FacesContext.getCurrentInstance().addMessage(null, msg); 
        
    }  
      
    public void onCancel(RowEditEvent event) {  
        
    }  

    private void chargeData() {
        List< String > privSource = new CreateRolBean().initPrivileges();
        List< String > privTarget = getPrivRol(selectedRol.getName() );
        System.out.println("PRIV TARGET");
        for( String s: privTarget ){
            System.out.println(" PT->> "+s);
            privSource.remove( s );
        }
        
        privileges = new DualListModel<>(privSource, privTarget);
    }

    private List<String> getPrivRol(String name) {
        FacesMessage msg = new FacesMessage();  
          
        ArrayList<String> res = new ArrayList<>();
        try {
            
            res = new RolBusiness( conn ).getPrivileges( name );
            
            msg.setSeverity(FacesMessage.SEVERITY_INFO);  
            //msg.setSummary("Privilegios");
            //msg.setDetail("Mostrados Exitosamente");  
            //FacesContext.getCurrentInstance().addMessage(null, msg);  
            return res;
        } catch (SQLException ex) {
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);  
            msg.setSummary("ERROR!");
            msg.setDetail("Fallo al cargar privilegios "+ex);  
            FacesContext.getCurrentInstance().addMessage(null, msg);  
        }
        return res;
    }
    
    public void onTransfer(TransferEvent event) {  
        StringBuilder builder = new StringBuilder();  
        RolBusiness rb = new RolBusiness( conn );
        FacesMessage msg = new FacesMessage();  
        
        for(Object item : event.getItems()) {  
            //System.out.println("OnTRansfer: "+ (String) item);
            if( privileges.getTarget().contains((String) item) ){
                try {
                    rb.addPrivileges( (String) item, selectedRol.getName() );
                    builder.append( (String) item );
                } catch (SQLException ex) {
                    msg = new FacesMessage();  
                    msg.setSeverity(FacesMessage.SEVERITY_FATAL);  
                    msg.setSummary("Error al asignar Privilegio");
                    msg.setDetail("Privilegio: "+item + " " + ex.getMessage());  

                    FacesContext.getCurrentInstance().addMessage(null, msg);  
                }
            }else {
                try {
                    rb.revokePrivileges( (String) item, selectedRol.getName());
                    builder.append( (String) item );
                } catch (SQLException ex) {
                    msg = new FacesMessage();  
                    msg.setSeverity(FacesMessage.SEVERITY_FATAL);  
                    msg.setSummary("Error al revocar Privilegio");
                    msg.setDetail("Privilegio: "+item + " " + ex.getMessage());  

                    FacesContext.getCurrentInstance().addMessage(null, msg);  
                }
            }
            
        }  
        
        
        msg = new FacesMessage();  
        msg.setSeverity(FacesMessage.SEVERITY_INFO);  
        msg.setSummary("Items Transferidos:");
        msg.setDetail(builder.toString());  
          
        FacesContext.getCurrentInstance().addMessage(null, msg);  
    }  
    
}
